package com.pospi.pai.yunpos.report;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.caigou.CgddBeen;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;
import com.pospi.util.GetData;


import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

public class StoreReportActivity extends Base2Activity {
//    @Bind(R.id.tv_xsmc)
//    TextView tv_xsmc;
//    @Bind(R.id.tv_xsmd)
//    TextView tv_xsmd;
    @Bind(R.id.tv_xsje)
    TextView tv_xsje;

//    @Bind(R.id.tv_kcmd)
//    TextView tv_kcmd;
    @Bind(R.id.tv_kcje)
    TextView tv_kcje;
    @Bind(R.id.tv_kcsl)
    TextView tv_kcsl;
    @Bind(R.id.time_start_select)
    TextView time_start_select;
    @Bind(R.id.time_end_select)
    TextView time_end_select;


//    @Bind(R.id.tv_cgmc)
//    TextView tv_cgmc;
//    @Bind(R.id.tv_cgmd)
//    TextView tv_cgmd;
    @Bind(R.id.tv_cgje)
    TextView tv_cgje;
    @Bind(R.id.tv_thje)
    TextView tv_thje;

//    @Bind(R.id.tv_tbmc)
//    TextView tv_tbmc;
//    @Bind(R.id.tv_tbmd)
//    TextView tv_tbmd;
    @Bind(R.id.tv_trje)
    TextView tv_trje;
    @Bind(R.id.tv_tcje)
    TextView tv_tcje;
//
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.bt_search)
    TextView bt_search;
    @Bind(R.id.tv_syje)
    TextView tv_syje;



    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    List<String> strings = new ArrayList<>();

    private List<CgddBeen> beens = new ArrayList<>();
    private String count;
    private String je;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.mdjy_list_item);
        ButterKnife.bind(this);
        setTitle("门店经营");
        setMenuImage(R.drawable.icon_search_white);
        downmd();
        tv_md.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showmd(tv_md);
            }
        });

        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchxs();
            }
        });
        time_start_select.setText(GetData.getYYMMDDTime());
        time_end_select.setText(GetData.getYYMMDDTime());
        time_end_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar c = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(StoreReportActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                        c.set(year, monthOfYear, dayOfMonth);
                        time_end_select.setText(DateFormat.format("yyyy-MM-dd", c));
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                dialog.show();
//                TimePickerDialog dialogYearMonthDay2 = new TimePickerDialog.Builder()
//                        .setType(Type.YEAR_MONTH_DAY)
//                        .setTitleStringId("选择日期")
//                        .setWheelItemTextSize(16)
//                        .setCallBack(new OnDateSetListener() {
//                            @Override
//                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
//                                Date date = new Date(millseconds);
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                String time = format.format(date);
//                                time_end_select.setText(time);
//                            }
//                        })
//                        .build();
//                dialogYearMonthDay2.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
            }
        });
        time_start_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar c = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(StoreReportActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                        c.set(year, monthOfYear, dayOfMonth);
                        time_start_select.setText(DateFormat.format("yyyy-MM-dd", c));
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                dialog.show();
//                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
//                        .setType(Type.YEAR_MONTH_DAY)
//                        .setTitleStringId("选择日期")
//                        .setWheelItemTextSize(16)
//                        .setCallBack(new OnDateSetListener() {
//                            @Override
//                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
//                                Date date = new Date(millseconds);
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                String time = format.format(date);
//                                time_start_select.setText(time);
//                            }
//                        })
//                        .build();
//                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
            }
        });
        init();
//        downStore();
    }
//    @Override
//    public void onMenuClick(View view) {
//        super.onMenuClick(view);
//        Intent intent = new Intent(this, StoreReportSearchActivity.class);
//        startActivity(intent);
//
//    }



    private void init() {

//        switch_button.setText("今天","昨天","近三天","近七天","近一月");
//        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
//            @Override
//            public void onSwitch(int position, String tabText) {
//                switch (position) {
//                    case 0:
//                        md = "所有门店";
//                        startrq = GetData.getAnyTime(0);
//                        endrq = GetData.getAnyTime(0);
//                        startDown();
//                        break;
//                    case 1:
//                        md = "所有门店";
//                        startrq = GetData.getAnyTime(1);
//                        endrq = GetData.getAnyTime(1);
//                       startDown();
//                        break;
//                    case 2:
//                        md = "所有门店";
//                        startrq = GetData.getAnyTime(3);
//                        endrq = GetData.getAnyTime(0);
//                       startDown();
//                        break;
//                    case 3:
//                        md = "所有门店";
//                        startrq = GetData.getAnyTime(7);
//                        endrq = GetData.getAnyTime(0);
//                        startDown();
//                        break;
//                    case 4:
//                        md = "所有门店";
//                        startrq = GetData.getAnyTime(30);
//                        endrq = GetData.getAnyTime(0);
//                        startDown();
//                        break;
//                }
//            }
//        });
        startDown();

    }
    private void startDown(){
        searchxs();
    }

    private String marktId = "";
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch_button.clearSelection();
        startrq = intent.getStringExtra("startrq");
        endrq= intent.getStringExtra("endrq");
        marktId = intent.getStringExtra("market");
        md = intent.getStringExtra("marketname");
        searchxs();
    }

    private String rkjjje = "";
    private String tcjjje = "";
    private String syjje = "";
    private String xsjjje = "";
    private String xslsjje = "";

    private String dboutjjje = "";
    private String dbinjjje = "";
    private String pdjjje = "";
    private String psoutjjje = "";
    private String psinjjje = "";
    private String kcsl = "";
    private String kcjjje = "";



    //销售查询
    private void searchxs() {
        showLodingDialog();
        Map<String,String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "report.Mobile");
        params.put("fun", "find_markthz");

        JSONObject object = new JSONObject();
        try {
            object.put("startrq", time_start_select.getText().toString());
            object.put("endrq",time_end_select.getText().toString());
            object.put("market", mdid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("report", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    Log.i("login", jsonObject.getString("errMsg"));
                    JSONObject result = jsonObject.getJSONObject("result");
                    rkjjje = result.getString("rkjjje");
                    tcjjje = result.getString("tcjjje");
                    syjje = result.getString("syjje");
                    xslsjje = result.getString("xslsjje");
                    dboutjjje = result.getString("dboutjjje");

                    dbinjjje = result.getString("dbinjjje");
                    kcjjje = result.getString("kcjjje");
                    kcsl = result.getString("kcsl");



                } catch (JSONException e) {

                    e.printStackTrace();
                }
                Message message = Message.obtain();
                message.what = 1;
                handler.sendMessage(message);
            }
        });

    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeLodindDialog();
                    setData();

                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };
    private String md = "所有门店";

    private void setData() {
        tv_xsje.setText(xslsjje);
        tv_kcje.setText(kcjjje);
        tv_kcsl.setText(kcsl);
        tv_cgje.setText(rkjjje);
        tv_thje.setText(tcjjje);
        tv_trje.setText(dbinjjje);
        tv_tcje.setText(dboutjjje);
        tv_syje.setText(syjje);
//
//        tv_xsmd.setText(md);
//        tv_kcmd.setText(md);
//        tv_cgmd.setText(md);
//        tv_tbmd.setText(md);
//        tv_symd.setText(md);

    }

    private void setbill(boolean o){
        if (o) {

        } else {

            beens.clear();
        }

    }

    //下载
    private void downmd() {
        Map<String,String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                    md_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }

    private String mdid = "";
    private void creatDialogMarket(final List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        tv_md.setText(ss.get(i));
                        mdid = md_Beens.get(i).getId();

                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }


    private String startrq = "";
    private String endrq = "";

    private void showmd(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : md_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_md.setText(md_Beens.get(position).getName());
                mdid = md_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

}
